/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BLL;

import DAL.ConnectData;
import DTO.Category;
import java.sql.ResultSet;
import java.util.ArrayList;

/**
 *
 * @author Vien-IT
 */
public class BCategory {
    
    private ConnectData condata;

    public BCategory() {
        condata = new ConnectData();
    }
    
    public ArrayList<Category> getAll(String sql)
    {
        ArrayList<Category> categories = new ArrayList<Category>();
        Category category = null;
        try {
            ResultSet rs = condata.executeQuery(sql);
            while(rs.next())
            {
                category = new Category();
                category.setCategoryId(rs.getInt("categoryId"));
                category.setName(rs.getString("name"));
                category.setParent(rs.getInt("parent"));
                categories.add(category);
                
            }
           
        } catch (Exception e) {
        }
        finally
        {
        	 condata.close();
        }
        
        return categories.isEmpty() ? null : categories;
    }
    
    public ArrayList<Category> getAll()
    {
        String sql = "select * from tblCategory";
           return getAll(sql);
    }
    
    public ArrayList<Category> getRoot()
    {
        String sql = "SELECT * FROM tblcategory WHERE parent = 0";
           return getAll(sql);
    }
    
    public ArrayList<Category> getByParent(int parent)
    {
        String sql = "SELECT * FROM tblcategory WHERE parent = "+parent;
           return getAll(sql);
    }
    
    
    
    
    public Category getById(int categoryId)
    {
        String sql = "select * from tblCategory where CategoryId = "+categoryId+"";
        ArrayList<Category> categories = getAll(sql);
        return categories == null ? null : categories.get(0);
    }
    
    
    public boolean insert(Category category)
    {
        boolean check = false;
        String sql = "insert into tblCategory (name, parent) "
                + "values ('"+category.getName()+"',"+category.getParent()+")";
        int rs = -1;
        try {
            rs = condata.executeUpdate(sql);
            if(rs > 0)
                check = true;
        } catch (Exception e) {
        }
        return check ;
    }
    
}
